import cv2
import numpy as np

def detect_nudity(image_path, threshold=0.2):
    # 读取图像
    image = cv2.imread(image_path)
    if image is None:
        raise FileNotFoundError("无法加载图像，请检查路径")
    
    # 转换为 HSV 颜色空间
    hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    
    # 定义优化后的肤色 HSV 范围
    lower_skin = np.array([0, 10, 60], dtype=np.uint8)
    upper_skin = np.array([50, 200, 255], dtype=np.uint8)
    
    # 创建肤色掩码
    skin_mask = cv2.inRange(hsv_image, lower_skin, upper_skin)
    
    # 进行形态学操作，去除噪点
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    skin_mask = cv2.morphologyEx(skin_mask, cv2.MORPH_OPEN, kernel)
    skin_mask = cv2.morphologyEx(skin_mask, cv2.MORPH_CLOSE, kernel)
    
    # 计算肤色区域占比
    skin_pixels = cv2.countNonZero(skin_mask)
    total_pixels = image.shape[0] * image.shape[1]
    skin_ratio = skin_pixels / total_pixels
    
    # 根据阈值判断是否为裸露
    return skin_ratio > threshold

# 测试图片
image1 = "PVC-Figures-You_00022_.png"
image2 = "PVC-Figures-You_00023_.png"
image3 = "PVC-Figures-You_00024_.png"

result1 = detect_nudity(image1)
result2 = detect_nudity(image2)
result3 = detect_nudity(image3)

print(f"图像1是否包含裸体内容: {result1}")
print(f"图像2是否包含裸体内容: {result2}")
print(f"图像3是否包含裸体内容: {result3}")